/**
 * 首页推荐设置
 */
var BSTMG = BSTMG || {};
BSTMG.indexmanager = {
	flag: { flag_firstselect : true },
	$OBJS : {},
	init: function(){
		var that = this;
		/* 初始化选项卡 */
		that.initJqObjs();
		/* 绑定操作 */
		that.bindOperators();
	},
	/* 展示区块，参数为类名 */
	switchArea: function($area,certain){
		for(var key in $area){
			key == certain ? $area[key].show() : $area[key].hide();
		};
	},
	initJqObjs: function(){
		var that = this,
			$objs = that.$OBJS;
		$objs["sec1"] = $("#sec1");
		$objs["sec2"] = $("#sec2");
		// 选项卡区块
		$objs["switch"] = [];
		$objs["switch"][0] = {
				"sec1": $objs["sec1"],
				"sec2": $objs["sec2"]
		};
	},
	initCategoryTree: function(){
		var that = this,
			$categoryTree = $("#categoryTree"),
			$body = $("body"),
			$selTreeCombine = $(".selTreeCombine"),
			$selbox = $selTreeCombine.find(".seltreebox");
		var settingcatogory = {
				view: {
					showIcon: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: null ,
					onClick: setCategory
				}
			};
		try{
			var $ztree = $.fn.zTree.init( $categoryTree , settingcatogory , zNodes );
			
			$selTreeCombine.on("click","input",function(){
				var $this = $(this);
				showCategoryTree.apply(this);
				that.flag.flag_firstselect ? fistSelectTreeNode.apply(this) : that.flag.flag_firstselect = false ;
			}).on("keydown","input",function(){
				return false;
			});
			// 显示隐藏
			function showCategoryTree() {
				$(this).next(".seltreebox").show();
			};
			// 关闭下拉树
			function onBodyDownCloseTree(event){
				if ( !( $(event.target).parents(".selTreeCombine").length > 0 ) ) {
					$selbox.hide();
				};
			};
			// 第一次默认选中input内容
			function fistSelectTreeNode(){
				var $this = $(this),
					id = $this.data("id");
				$body.off( "mousedown" , onBodyDownCloseTree );
				if( $ztree.getNodesByParam("id", id )[0] ){
					$("#" + $ztree.getNodesByParam("id", id )[0].tId + '_a').trigger("click");
				};
				$body.on("mousedown" , onBodyDownCloseTree );
				that.flag.flag_firstselect = false ;
			};
		}catch(e){
			BSTYUN.dialog.warn("分类树初始化失败！请检查数据。");
		};
		// 显示分类
		function setCategory( event,treeId,treeNode,clickFlag ){
			var id = treeNode.id ,
				name = treeNode.name ,
				pId = treeNode.pId ,
				level = treeNode.level;
			var $treeinput = $( "#"+treeId ).parent().prev();
			$treeinput.val( name ).data({
				"id" : id ,
				"level" : level
			});
			$body.trigger("mousedown");
		};
	},
	bindOperators: function(){
		var that = this,
			status = 0,				//0 查看； 1 新增； 2 编辑
			$addnew = $(".addnew"),
			$cancel = $(".cancel"),
			$confirm = $(".confirm");
		var $name = $("#moduleName"),
			$category = $("#moduleCategory"),
			$moduleNum = $("#moduleNum");
		var $table = $("#indextable");
		$addnew.on("click",function(){
			// 新增
			$name.val('');
			$category.val('').data({
				"id": undefined,
				"level": undefined
			});
			$moduleNum.val('');
			status = 1;
			that.switchArea( that.$OBJS["switch"][0] , "sec2" );
		});
		$cancel.on("click",function(){
			// 取消保存
			that.switchArea( that.$OBJS["switch"][0] , "sec1" );
		});
		$table.on("click",".indexmodelook",function(){
			var $this = $(this),
				id = $.trim( $this.parent().attr("data-id") );
			// 查看 填充内容ajax请求
			status = 0;
			fillData( id );
			that.switchArea( that.$OBJS["switch"][0] , "sec2" );
		}).on("click",".indexmodeedit",function(){
			var $this = $(this),
				id = $.trim( $this.parent().attr("data-id") );
			// 编辑 填充内容ajax请求
			status = 2;
			fillData( id );
			that.switchArea( that.$OBJS["switch"][0] , "sec2" );
		}).on("click",".indexmodedelete",function(){
			var $this = $(this),
				id = $.trim( $this.parent().attr("data-id") );
			BSTYUN.dialog.confirm("确定要删除此条数据？",function(){
				$.ajax({
					url: '/sysAdmin/operate/indexGroomAdmin/deleteByModuleId',
					type: 'post',
					dataType: 'json',
					data: {id: id},
					beforeSend: function(){},
					complete: function(){},
					success: function( data ){
						// 成功删除
						if(data.isDelete){
							location.href = "/sysAdmin/indexGroomAdmin";
						}else{
							BSTYUN.dialog.warn("操作失败！请重新操作！");
						}
					},
					error: function(){}
				});
			});
		}).on("click",".indexmodestop",function(){
			var $this = $(this),
				id = $.trim( $this.parent().attr("data-id") );
			indexModelToggle(id,1);
		}).on("click",".indexmodestart",function(){
			var $this = $(this),
				id = $.trim( $this.parent().attr("data-id") );
			indexModelToggle(id,0);
		});
		$confirm.on("click",function(){
			// 确定保存
			var data = getData();
			if( !checkData( data ) ) return;
			status == 0 ? BSTYUN.dialog.warn("只有编辑和新增时该按钮才有效！") : sendAjax( data );
		});
		// 获取数据
		function getData(){
			return {
				name: $.trim( $name.val() ),
				id: $.trim( $name.data('id') ),
				categoryname: $.trim( $category.val() ),
				categoryid: $.trim( $category.data("id") ),
				categorylevel: $.trim( $category.data("level") ),
				num: $.trim( $moduleNum.val() )
			};
		};
		// 校验数据
		function checkData( data ){
			if( data.name == '' ){
				BSTYUN.dialog.warn("模块名称不能为空！");
				return false;
			};
			if( data.categoryid == '' ){
				BSTYUN.dialog.warn("显示类别不能为空！");
				return false;
			};
			if( data.num == '' ){
				BSTYUN.dialog.warn("排列顺序不能为空！");
				return false;
			};
			if( !/^[1-9]$|10/.test( data.num )  ){
				BSTYUN.dialog.warn("排列顺序必须为1-10的整数！");
				return false;
			};
			return true;
		};
		// 新增 编辑 提交
		function sendAjax( data ){
			$.ajax({
				url: '/sysAdmin/operate/indexGroomAdmin/saveIndexModule',
				type: 'post',
				dataType: 'json',
				data: data,
				beforeSend: function(){},
				complete: function(){},
				success: function( data ){
					if(data.isSuccess){
						location.href = "/sysAdmin/indexGroomAdmin";
					}else{
						BSTYUN.dialog.warn("操作失败！请重新操作！");
					}
				},
				error: function(){}
			});
		};
		// 查看 编辑 填充数据
		function fillData( id ){
			$.ajax({
				url: '/sysAdmin/indexGroomAdmin/selectIndexModuleInfo',
				type: 'post',
				dataType: 'json',
				data: {id: id},
				beforeSend: function(){},
				complete: function(){},
				success: function( data ){
					if(data.isOk){
						var indexModule = data.indexModule;
						$name.val(indexModule.moduleName).data("id",id);
						$category.val(indexModule.typeName).data({
							"id": indexModule.typeId,
							"level": indexModule.typeName 
						});
						$moduleNum.val(indexModule.moduleNum);
					}else{
						BSTYUN.dialog.warn("查询失败！");
					}
					
				},
				error: function(){}
			});
		};
		//显示或者隐藏
		function indexModelToggle(id,state){
			BSTYUN.dialog.confirm("确定要设置吗？",function(){
				$.ajax({
					url: '/sysAdmin/indexGroomAdmin/selectIndexModuleById',
					type: 'post',
					dataType: 'json',
					data: {
						id: id,
						state:state 
					},
					beforeSend: function(){},
					complete: function(){},
					success: function( data ){
						if(data.isShow){
							location.href = "/sysAdmin/indexGroomAdmin";
						}else{
							BSTYUN.dialog.warn("操作失败！请重新操作！");
						}
					},
					error: function(){}
				});
			});
		}
	}
};

$(function(){
	BSTMG.indexmanager.init();
});